CONTACTS.Search = {
	
	//set class name for input fields
	contact_field_class_name : 'contact_field_',

	/**********************************************************************
	 * Create event handlers and/or perform other initializations
	 *********************************************************************/
	initialize : function() {

		//search database every time the search box is changed (key press)
		$('#field_query').keyup(function() { CONTACTS.Search.perform_search(); });
		
		//on load of contacts screen, perform search
		CONTACTS.Search.perform_search();
					
		//handle changes to the checkboxes
			$('#form_search input[type=checkbox]').click(function(){
				
				//if neither persons nor companies is checked, re-check persons/companies
				if ($(this).hasClass('checkbox_persons') || $(this).hasClass('checkbox_companies')) {
					if ( !$('.checkbox_persons').attr('checked') && !$('.checkbox_companies').attr('checked') ) {
						$(this).attr('checked','checked');
					}
				}
			
				//default: "all", cannot be unchecked
				if ($(this).hasClass('checkbox_all')) {
					$(this).attr('checked','checked');
					$('#form_search input[type=checkbox]').each(function(){
						if ( !$(this).hasClass('checkbox_persons') && !$(this).hasClass('checkbox_companies') && !$(this).hasClass('checkbox_all') ) {
							$(this).attr('checked','');
						}
					});
				}
				
				//if check "employees" or contact types, uncheck "all"
				if ( !$(this).hasClass('checkbox_persons') && !$(this).hasClass('checkbox_companies') && !$(this).hasClass('checkbox_all') ) {
					if ($(this).attr('checked')) {
						$('.checkbox_all').attr('checked','');
					}
					
				}
				
				//if check "employees" and all contact types, back to default
				var checked_all = true;
				//if "employees" is unchekced, and all contact types are unchecked, back to default
				var checked_none = true;
				$('#form_search input[type=checkbox]').each(function(){
					if ( !$(this).hasClass('checkbox_persons') && !$(this).hasClass('checkbox_companies') && !$(this).hasClass('checkbox_all') ) {
						if (!$(this).attr('checked')) {
							checked_all = false;
						} else {
							checked_none = false;
						}
					}
				});
				if (checked_all || checked_none) {
					$('.checkbox_all').attr('checked','checked');
					$('#form_search input[type=checkbox]').each(function(){
						if ( !$(this).hasClass('checkbox_persons') && !$(this).hasClass('checkbox_companies') && !$(this).hasClass('checkbox_all') ) {
							$(this).attr('checked','');
						}
					});			
				}
			
				//perform search
				$('#field_query').trigger('keyup');
			});
		
		//scroll to letter in contact list on click
			$('a[id^=link_directory_]').click(function(){
				$('#search_results').scrollTo( $('#contact_list_'+ ( $(this).attr('id').substring($(this).attr('id').length-1,$(this).attr('id').length) )) , 400);
			});
			
		// ---------------------------------------------------------------------------------------------------------------
		// Contacts - more info
		// ---------------------------------------------------------------------------------------------------------------

		//more info of contact on click of name in contact list ---------------------------------
		
			$('.search_result_item a').live('click',function(){

				//hide notification box
				COMMON.hide_notification('.container-search-results .box');
				
				//hide the contact details box
				$('.container-contact-details').hide('slow');
				$('.container-company-info').hide('slow');

				//show loading animation
				$('.container-search-results .loader').show();

				//define error handler
				var error_occurred = function() {
					COMMON.show_notification('.container-search-results .box','box-error','Error occurred. Please try again.',null);
					$('.container-search-results .loader').hide();
				};

				//prepare data
				var contact_id = $(this).attr('data-contact_id');
				var category = $(this).attr('data-is_person') == 'y' ? 'person' : 'company';
				data = { 'contact_id':contact_id, 'category':category };
				
				$.ajax({
					type: 'POST',
					url: 'contacts/ajax_get_contact_details',
					data: { 'json':JSON.stringify(data) },
					dataType: 'json',
					success: function(return_data) {
						
						if (return_data) {
							
							//prepare display of contact fields
							var contact_fields = '';
							var last_field = '';
							var count = 0;
							for (i in return_data['contact_fields']) {
								if (last_field == return_data['contact_fields'][i]['name']) {
									contact_fields += '<br />' + return_data['contact_fields'][i]['value'];
								} else {
									if (count>0) {
										contact_fields += '</p>';
									}
									contact_fields += '<p><b>' + return_data['contact_fields'][i]['name'] + '</b><br />' + return_data['contact_fields'][i]['value'];
								}
								count++;							
								last_field = return_data['contact_fields'][i]['name'];
							}

							//display the contact information
							if (return_data['contact']['is_person']=='y') {
							
								//show the contact detail box
								$('.container-contact-details').show('slow',function(){});
								
								$('.container-contact-details .contact_name').html(return_data['contact']['name']);
								$('.container-contact-details .contact_company').html(return_data['contact']['company_name']);
								$('.container-contact-details .contact_types').html(return_data['contact']['contact_types']);
								$('.container-contact-details .contact_fields').html(contact_fields);
							
							} else if (return_data['contact']['is_person']=='n') {

								//show the company info box
								$('.container-company-info').show('slow',function(){});
								
								$('.container-company-info .contact_name').html(return_data['contact']['company_name']);
								$('.container-company-info .contact_types').html(return_data['contact']['contact_types']);
								$('.container-company-info .contact_fields').html(contact_fields);

							}
							
							$('.container-search-results .loader').hide();
							
							
							
							
						} else {
							error_occurred();
						}
					},
					error: error_occurred
				});
				
				
				return false;
			});
		
		//inline "popup" ------------------------------------------------------------------------
		
			$('.pop-in-link').each(function() {
				$(this).click(function() {
					var target_pop_in = $(this).attr('rel');
					var target_pop_out = $(this).attr('rev');
					$('.' + target_pop_out).hide('slow',function(){ $('.' + target_pop_in).show('slow',function(){ $('#pop-in-back-button').slideToggle('fast'); }); });
					return false;
				});
			});
			

		// ---------------------------------------------------------------------------------------------------------------
		// New Person
		// ---------------------------------------------------------------------------------------------------------------

		//reset popup new person -----------------------------------------------------------------
		
			$('#link_new_person').click(function(){
				
				//hide notification box
				COMMON.hide_notification('#form_new_person .box');

				//show "loading" animation
				$('.popup_new_person .loader').show();

				//define error handler
				var error_occurred = function() {
					COMMON.show_notification('#form_new_person .box','box-error','Error occurred. Please try again.',{target:'.popup_new_person',width:0,height:50});
					$('.popup_new_person .loader').hide();
				};

				//populate contact types and companies
				$.ajax({
					type: 'POST',
					url: 'contacts/ajax_get_new_contact_fields',
					data: { },
					dataType: 'json',
					success: function(return_data) {
						if (return_data) {
							$('#form_new_person .field_company_id option').remove();
							$('#form_new_person .field_company_id').append('<option value="-1">[None]</option>');
							for (i in return_data['companies']) {
								$('#form_new_person .field_company_id').append('<option value="' + i + '">' + return_data['companies'][i] + '</option>');
							}
							$('#form_new_person .contact_types').html('<label class="choice"><input type="checkbox" value="employee" class="contact_type" /> ' + COMMON.company_name +' Employee<br /></label>');
							for (i in return_data['contact_types']) {
								$('#form_new_person .contact_types').html($('#form_new_person .contact_types').html() + '<label class="choice"><input type="checkbox" value="' + i + '" class="contact_type" /> ' + return_data['contact_types'][i] + '<br /></label>');
							}
							$('.popup_new_person .loader').hide();
						} else {
							error_occurred();
						}
					},
					error: error_occurred
				});				
				
				//reset fields to blank
				$('#form_new_person table .contact_type_field').remove();
				$('#form_new_person input[type=text]').val('');
				$('#form_new_person .field_company_id').val('-1');
				$('#form_new_person .field_contact_type_ids input[type=checkbox]').each(function(){
					$(this).attr('checked','');
				});
				
				//return false so that the href of the button will not be followed
				return false;
			});

		//event hander for save new person -------------------------------------------------------
		
			$('#button_save_new_person').click(function() {
		
				//hide notification box
				COMMON.hide_notification('#form_new_person .box');
						
				//prepare the data to be sent
				var form_data = {};
				form_data['first_name'] = $('#form_new_person .field_first_name').val();
				form_data['last_name'] = $('#form_new_person .field_last_name').val();
				form_data['company_id'] = $('#form_new_person .field_company_id').val();
				form_data['contact_type_ids'] = [];
					$('#form_new_person .field_contact_type_ids :checked').each(function(){
						form_data['contact_type_ids'].push($(this).val());
					});
				form_data['contact_fields'] = {};
					$('#form_new_person input[class^=' + CONTACTS.contact_field_class_name + ']').each(function() {
						var loc = form_data['contact_fields'][$(this).attr('className').replace(CONTACTS.contact_field_class_name,'')];
						if ( loc instanceof Array ) {
							loc.push($(this).val());
						} else {
							form_data['contact_fields'][$(this).attr('className').replace(CONTACTS.contact_field_class_name,'')] = [$(this).val()];
						}
					});
					
				//validate
				if ($.trim(form_data['first_name'])=='' || $.trim(form_data['last_name'])=='') {
					COMMON.show_notification('#form_new_person .box','box-error','First and last names are required.',{target:'.popup_new_person',width:0,height:50});
					return false;
				}
				
				//show "loading" animation
				$('.popup_new_person .loader').show();
				
				//define error handler
				var error_occurred = function() {
					COMMON.show_notification('#form_new_person .box','box-error','Error occurred. Please try again.',{target:'.popup_new_person',width:0,height:50});
					$('.popup_new_person .loader').hide();
				};
				
				//send the data
				$.ajax({
					type: 'POST',
					url: 'contacts/ajax_save_new_person',
					data: { 'json':JSON.stringify(form_data) },
					dataType: 'text',
					success: function(return_data) {
						if (return_data=='1') {
							$('.popup_new_person .loader').hide();
							$('.popup_new_person .nyroModalClose').trigger('click');
						} else {
							error_occurred();
						}
					},
					error: error_occurred
				});
				
				//return false so that the href of the button will not be followed
				return false;
		
			});
			
			//add or remove contact fields on change of contact types ------------------------------------
			
				$('#form_new_person .field_company_id').live('change',function() { CONTACTS.Search.update_contact_fields(); });
				$('#form_new_person .contact_type').live('click',function() { CONTACTS.Search.update_contact_fields(); });
				
				//action for 'add' another field
				$('.button_add').live('click',function(){
					$(this).parent().parent().clone().find('input[class^='+CONTACTS.contact_field_class_name+']').val('').parent().append('<a href="#" class="button_delete" rel=".popup_new_person"><img src="'+COMMON.webroot+'/images/icons/delete.png" /></a>').parent().find('td:nth-child(1)').html('').parent().insertAfter($(this).parent().parent());
					COMMON.resize_modal($(this).attr('rel'),0,50);
				});
			
				//action for 'delete' another field
				$('.button_delete').live('click',function(){
					$(this).parent().parent().remove();
					COMMON.resize_modal($(this).attr('rel'),0,50);
				});
			
		// ---------------------------------------------------------------------------------------------------------------
		// New Company
		// ---------------------------------------------------------------------------------------------------------------

		//reset popup new company -----------------------------------------------------------------
		
			$('#link_new_company').click(function(){

				//hide notification box
				COMMON.hide_notification('#form_new_company .box');

				//show "loading" animation
				$('.popup_new_company .loader').show();

				//define error handler
				var error_occurred = function() {
					COMMON.show_notification('#form_new_company .box','box-error','Error occurred. Please try again.',{target:'.popup_new_company',width:0,height:50});
					$('.popup_new_company .loader').hide();
				};

				//populate contact types and companies
				$.ajax({
					type: 'POST',
					url: 'contacts/ajax_get_new_contact_fields',
					data: { },
					dataType: 'json',
					success: function(return_data) {
						if (return_data) {
							for (i in return_data['contact_types']) {
								$('#form_new_company .contact_types').html($('#form_new_company .contact_types').html() + '<label class="choice"><input type="checkbox" value="' + i + '" class="contact_type" /> ' + return_data['contact_types'][i] + '<br /></label>');
							}
							$('.popup_new_company .loader').hide();
						} else {
							error_occurred();
						}
					},
					error: error_occurred
				});				
				
				//reset fields to blank
				$('#form_new_company .field_name').val('');
				$('#form_new_company input[type=checkbox]').each(function(){
					$(this).attr('checked','');
				});
			});

		//event hander for save new company -------------------------------------------------------
		
			$('#button_save_new_company').click(function() {
				
				//hide notification box
				COMMON.hide_notification('#form_new_company .box');
		
				//prepare the data to be sent
				var form_data = {};
				form_data['name'] = $('#form_new_company .field_name').val();
				form_data['contact_type_ids'] = [];
				$('#form_new_company .field_contact_type_ids :checked').each(function(){
					form_data['contact_type_ids'].push($(this).val());
				});
		
				//validate
				if ($.trim(form_data['name'])=='') {
					COMMON.show_notification('#form_new_company .box','box-error','Company name is required.',{target:'.popup_new_company',width:0,height:0});
					return false;
				}
		
				//show "loading" animation
				$('.popup_new_company .loader').show();
				
				//define error handler
				var error_occurred = function() {
					COMMON.show_notification('#form_new_company .box','box-error','Error occurred. Please try again.',{target:'.popup_new_company',width:0,height:0});
					$('.popup_new_company .loader').hide();
				};
								
				//send the data
				$.ajax({
					type: 'POST',
					url: 'contacts/ajax_save_new_company',
					data: { 'json':JSON.stringify(form_data) },
					dataType: 'text',
					success: function(return_data) {
						if (return_data=='1') {
							$('.popup_new_company .loader').hide();
							$('.popup_new_company .nyroModalClose').trigger('click');
						} else {
							error_occurred();
						}
					},
					error: error_occurred
				});
				
				//return false so that the href of the button will not be followed
				return false;
		
			});

	}, //end CONTACTS.Search.initialize()
	
	
	/**********************************************************************
	 * Performs the actual search
	 *********************************************************************/
	perform_search : function() {
		
		//hide notification box
		COMMON.hide_notification('#form_search .box');
		
		//show the loading animation
		$('#form_search .loader').show();
		
		var form_data = {};
		form_data['query'] = $('#field_query').val();
		form_data['options'] = [];
		$('#form_search .field_options :checked').each(function(){
			form_data['options'].push($(this).val());
		});
		
		//define error handler
		var error_occurred = function() {
			COMMON.show_notification('#form_search .box','box-error','Error occurred. Please try again.',null);
			$('#form_search .loader').hide();
		};

		//send the data
		$.ajax({
			type: 'POST',
			url: 'contacts/ajax_search',
			data: { 'json':JSON.stringify(form_data) },			
			dataType: 'json',
			success: function(return_data) {
				if (return_data) {
					
					//populate contact list with search results
					var html = '<div class="box hidden"></div>';
					var first_letter = '';
					
					for (i in return_data){
						
						var new_first_letter = return_data[i]['name'].charAt(0);
						if (first_letter !== new_first_letter) {
							html += '\
								<div id="search_results_header">\
                            		<h3><a id="contact_list_' + new_first_letter.toUpperCase() + '" name="contact_list_' + new_first_letter.toUpperCase() + '"></a>' + new_first_letter + '</h3>\
                            		<hr />\
                        		</div>\
							';
							first_letter = new_first_letter;
						}
													
						html += '\
							<div class="colgroup leading search_result_item">\
								<div class="column ta-center">\
									<img src="' + COMMON.webroot + '/images/preview-not-available.gif" alt="" />\
								</div>\
								<div class="width2 column">\
									<a href="#" data-contact_id="' + return_data[i]['contact_id'] + '" data-is_person="' + return_data[i]['is_person'] + '"><b class="big">'+ return_data[i]['name'] + '</b></a><br/>\
									<small><b class="contact_description">'+ ( (return_data[i]['description']) ? return_data[i]['description']+'<br />' : '' )+ '</b>\
									<span class="contact_description2"></span></small><br />\
								</div>\
							</div>\
							<div class="clearfix"></div>\
						';
					}
					$('#search_results').html(html);
					
					//hide the loading animation
					$('#form_search .loader').hide();
				} else {
					error_occurred();
				}
			},
			error: error_occurred
		});
		
		
	}, //end CONTACTS.Search.perform_search()
	
	
	/**********************************************************************
	 * Updates the list of contact fields that are editable
	 *********************************************************************/
	update_contact_fields : function() {
		
		//show "loading" animation
		$('.popup_new_person .loader').show();
		
		//define error handler
		var error_occurred = function() {
			COMMON.show_notification('#form_new_person .box','box-error','Error occurred: could not retrieve additional fields to fill out.',{target:'.popup_new_person',width:0,height:50});
			$('.popup_new_person .loader').hide();
		};

		//unselect all contact types
		if ($('#form_new_person .field_company_id').val()!='-1') {
			$('#form_new_person .field_contact_type_ids input[type=checkbox]').each(function(){
				$(this).attr('checked','');
			});
		}

		//prepare the data to be sent
		form_data = {
			contact_type_ids : [],
			contact_company_id : $('#form_new_person .field_company_id').val()
		};
		$('#form_new_person .contact_type:checked').each(function(){
			form_data['contact_type_ids'].push($(this).val());
		});
				
		//send the data
		$.ajax({
			type: 'POST',
			url: 'contacts/ajax_get_contact_fields',
			data: { 'json':JSON.stringify(form_data) },
			dataType: 'json',
			success: function(return_data) {

				if (return_data) {
					
					//show or hide contact types (show if 'no company', hide if a company is selected)
					if ($('#form_new_person .field_company_id').val()!='-1') {
						var contact_types = [];
						for (i in return_data['contact_types']) {
							contact_types.push(return_data['contact_types'][i]['name']);
						}
						$('.contact_types').hide();
						$('.inherited_contact_types').html(contact_types.join(', '));
					} else {
						$('.inherited_contact_types').html('');
						$('.contact_types').show();		
					}

					//save existing data
					var existing_data = [];
					$('#form_new_person table .contact_type_field input[type=text]').each(function(){
						var contact_field_id = ($(this).attr('className')+'').replace(CONTACTS.contact_field_class_name,'');
						existing_data[contact_field_id] = $(this).val();
					});
					
					//display fields and saved values (if any)
					$('#form_new_person table .contact_type_field').remove();
					for (i in return_data['contact_fields']) {						
						$('#form_new_person table').append('\
							<tr class="contact_type_field">\
								<td><a href="#" class="button_add" rel=".popup_new_person"><img src="'+COMMON.webroot+'/images/icons/add.png" /></a> ' + return_data['contact_fields'][i].name + '</td>\
								<td><input type="text" class="' + CONTACTS.contact_field_class_name + return_data['contact_fields'][i].contact_field_id + '" value="' + ( (existing_data[return_data['contact_fields'][i].contact_field_id]) ? existing_data[return_data['contact_fields'][i].contact_field_id] : '' ) + '" /> </td>\
							</tr>\
						');
					}
					COMMON.resize_modal('.popup_new_person',0,50);
					$('.popup_new_person .loader').hide();
				} else {
					error_occurred();
				}
			},
			error: error_occurred
		});
	} //end CONTACTS.Search.update_contact_fields()

};